﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Webcam.Image.Filters
{
    /// <summary>
    /// Removes noise using a median filter
    /// </summary>
    public class MedianFilter : ImageAction
    {
        public MedianFilter(RGBImage src)
            : base(src)
        {

        }

        /// <summary>
        /// Size of the window
        /// </summary>
        public int Window = 5;

        /// <summary>
        /// Process the image for differences
        /// </summary>
        public override void Process()
        {
            RGBImage img = src.Clone();

            int padding = Window / 2;
            for (int y = padding; y < src.Height - padding; y++)
            {
                int[] window = new int[Window];

                int pos = padding+1;
                for (int i = 0; i < padding; i++)
                {
                    window[i] = src[i, y].GrayScale;
                }
                for (int x = padding; x < src.Width - padding; x++)
                {
                    window[pos] = src[x+padding, y].GrayScale;
                    pos++;
                    if (pos == Window)
                        pos = 0;

                    int[] vals = (int[])window.Clone();
                    Array.Sort(vals);
                    RGB c = new RGB((byte)vals[padding + 1]);
                    img[x, y] = c;
                }
            }
            this.output = img;
        }
    }
}
